package org.example.diary.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.diary.entity.dao.Diary;
import org.example.diary.entity.dao.SysUser;
import org.example.diary.entity.dto.DiaryAddDTO;
import org.example.diary.entity.dto.LoginUser;
import org.example.diary.entity.vo.DiaryVO;
import org.example.diary.enums.BizErrorCode;
import org.example.diary.enums.DiaryHiddenEnums;
import org.example.diary.enums.StatusEnums;
import org.example.diary.exceptions.BizAssertUtil;
import org.example.diary.mapper.DiaryMapper;
import org.example.diary.mapper.UserMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DiaryServiceImpl implements DiaryService {

    @Resource
    private DiaryMapper diaryMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public String diaryAdd(DiaryAddDTO diaryAddDTO) {
        Diary diary = new Diary();
        BeanUtil.copyProperties(diaryAddDTO, diary);
        diary.setIsHidden(DiaryHiddenEnums.display.getStatus());
        diary.setIsDelete(StatusEnums.NORMAL.getStatus());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        diary.setUserId(loginUser.getSysUser().getId());

        diary.setCreateTime(LocalDateTime.now());
        diary.setUpdateTime(LocalDateTime.now());

        diaryMapper.insert(diary);
        return null;
    }

    @Override
    public String diaryUpdate(DiaryAddDTO diaryAddDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        Diary diary = diaryMapper.selectOne(new LambdaQueryWrapper<Diary>()
                .eq(Diary::getId, diaryAddDTO.getId())
                .eq(Diary::getUserId, loginUser.getSysUser().getId())
                .eq(Diary::getIsDelete, StatusEnums.NORMAL.getStatus())
        );
        BizAssertUtil.isTrue(Objects.isNull(diary), BizErrorCode.DATA_NOT_EXIST);
        BeanUtil.copyProperties(diaryAddDTO , diary , "id");

        diaryMapper.updateById(diary);
        return null;
    }

    @Override
    public PageInfo<DiaryVO> diaryList(Integer pageNum, Integer pageSize) {
        List<Long> userIds = getUserIds();
        PageHelper.startPage(pageNum, pageSize);
        //todo 这里不知道 管理隐藏后 用户能不能看到
        List<DiaryVO> diaryVOList = diaryMapper.selectDiaryList(userIds);
        return new PageInfo<>(diaryVOList);
    }

    @Override
    public String diaryDel(Integer diaryId) {
        Diary diary = getIdAndUserId(diaryId);
        BizAssertUtil.isTrue(Objects.isNull(diary), BizErrorCode.DATA_NOT_EXIST);

        diary.setIsDelete(StatusEnums.DELETED.getStatus());
        diaryMapper.updateById(diary);
        return null;
    }

    @Override
    public String diaryHide(Integer diaryId) {
        Diary diary = diaryMapper.selectOne(new LambdaQueryWrapper<Diary>()
                .eq(Diary::getId, diaryId)
                .eq(Diary::getIsDelete, StatusEnums.NORMAL.getStatus())
        );
        BizAssertUtil.isTrue(Objects.isNull(diary), BizErrorCode.DATA_NOT_EXIST);

        diary.setIsHidden(DiaryHiddenEnums.hide.getStatus());
        diaryMapper.updateById(diary);
        return null;
    }

    private Diary getIdAndUserId(Integer diaryId){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Diary diary = diaryMapper.selectOne(new LambdaQueryWrapper<Diary>()
                .eq(Diary::getId, diaryId)
                .eq(Diary::getUserId, loginUser.getSysUser().getId())
                .eq(Diary::getIsDelete, StatusEnums.NORMAL.getStatus())
        );
        return diary;
    }


    /**
     * 如果是管理源 则返回所有用户的id
     * 如果不是管理员 则返回自己的id
     * @return
     */
    public List<Long> getUserIds() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        SysUser sysUser = loginUser.getSysUser();
        Long role = sysUser.getRole();
        if (role == 1) {
            List<SysUser> sysUsers = userMapper.selectList(new LambdaUpdateWrapper<SysUser>());
            if (CollectionUtil.isNotEmpty(sysUsers)) {
                return sysUsers.stream().map(SysUser::getId).collect(Collectors.toList());
            }
        }
        return Collections.singletonList(sysUser.getId());
    }


}
